<template>
    <div class="admin-page">
    <div class="page-header">
      <div style="display: flex;justify-content: space-between">
          <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
              <div style="display: flex; align-items: center;" class="search-item">
                  <span class="search-label">日期:</span>
                  <el-date-picker
                      v-model="searchForm.date"
                      type="month"
                      size="small"
                      style="width: 130px;"
                      placeholder="选择日期"
                      value-format="yyyy-M"
                  />
              </div>
              <div style="display: flex; align-items: center;" class="search-item">
                  <span class="search-label">状态:</span>
                  <el-select v-model="searchForm.state" size="small" style="width: 110px;" placeholder="全部" clearable>
                      <el-option
                          v-for="item in statusOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                  </el-select>
              </div>
              <div style="display: flex; align-items: center;" class="search-item">
                  <span class="search-label">渠道用户:</span>
                  <el-select v-model="searchForm.channel_id" size="small" style="width: 110px;" placeholder="全部" clearable>
                      <el-option v-for="(item, index) in qudaoList" :key="index" :label="item.name" :value="item.id"></el-option>
                  </el-select>
              </div>
          </div>
          <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
              <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
              <el-button type="success" size="small" style="margin-left: 10px;" @click="handleReset">重置</el-button>
              <el-button type="success" size="small" style="margin-left: 10px;" @click="handleReset">发放</el-button>
              <el-button size="small" @click="exportToExcel">导出</el-button>
          </div>
      </div>

      <el-table :data="tableData" height="560" border style="width: 100%;overflow-y: auto"
                :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column prop="uid" label="用户ID" width="100" align="center" />
        <el-table-column prop="username" label="账号" width="100" align="center" />
        <el-table-column prop="name" label="渠道名称" width="100" align="center" />
        <el-table-column prop="year" label="年" width="100" align="center" />
        <el-table-column prop="month" label="月" width="100" align="center" />
        <el-table-column prop="total_price" label="渠道月份总业绩" width="150" align="center" />
        <el-table-column prop="is_up_name" label="分红时等级" width="100" align="center" />
        <el-table-column prop="ave_dis" label="平均分红" width="100" align="center" />
        <el-table-column prop="other_dis" label="加权分红" width="100" align="center" />
        <el-table-column prop="level_one_id" label="第一个业绩最小部门id" width="200" align="center" />
        <el-table-column prop="level_two_id" label="第二个最小部门id" width="200" align="center" />
        <el-table-column prop="level_one_money" label="第一个业绩最小部门业绩" width="200" align="center" />
        <el-table-column prop="level_two_money" label="第二个业绩最小部门业绩" width="200" align="center" />
          <el-table-column prop="state" label="发放状态" align="center" width="140">
              <template slot-scope="scope">
                  <div class="status-selector">
                      <el-select
                          v-model="scope.row.state.toString()"
                      size="small"
                      @change="(val) => changeLevel(scope.row.id, val)"
                      placeholder="选择状态"
                      class="status-dropdown"
                      >
                      <el-option label="待发放" value="0"></el-option>
                      <el-option label="已发放" value="1" disabled></el-option>
                      <el-option label="不发放" value="2"></el-option>
                      </el-select>
                  </div>
              </template>
          </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
      />
    </div>

    <!-- 金额修改弹窗 -->
    <el-dialog
      title="修改分成金额"
      :visible.sync="amountDialogVisible"
      width="450px"
      :close-on-click-modal="false"
      center
      :before-close="handleDialogClose"
      custom-class="amount-edit-dialog"
    >
      <el-form :model="editForm" label-width="70px" class="edit-form">
        <el-form-item label="用户ID:">
          <el-input v-model="editForm.userId" disabled class="info-item" size="small"></el-input>
        </el-form-item>
        <el-form-item label="用户名:">
          <el-input v-model="editForm.username" disabled class="info-item" size="small"></el-input>
        </el-form-item>
        <el-form-item label="原金额:">
          <el-input v-model="editForm.originalAmount" disabled class="info-item" size="small">
          </el-input>
        </el-form-item>
        <el-form-item label="新金额:">
          <el-input
            v-model="editForm.newAmount"
            type="number"
            size="small"
            placeholder="请输入新金额">
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="amountDialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="handleConfirmEdit" size="small">确认</el-button>
      </div>
    </el-dialog>

    <!-- 确认修改弹窗 -->
    <el-dialog
      title="确认修改"
      :visible.sync="confirmDialogVisible"
      width="400px"
      append-to-body
      center
      custom-class="confirm-dialog"
    >
      <div class="confirm-content">
        <i class="el-icon-warning-outline warning-icon"></i>
        <div class="confirm-text">
          <div class="confirm-title">确认修改</div>
          <div class="confirm-desc">您确定要将金额修改吗？此操作不可撤销！</div>
        </div>
      </div>
      <div class="confirm-details">
        <div class="detail-item">
          <span class="detail-label">用户ID:</span>
          <span class="detail-value">{{ editForm.userId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">用户名:</span>
          <span class="detail-value">{{ editForm.username }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">原金额:</span>
          <span class="detail-value">{{ editForm.originalAmount }} </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">新金额:</span>
          <span class="detail-value">{{ editForm.newAmount }} </span>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false" size="small">取消</el-button>
        <el-button type="success" @click="submitAmountChange" size="small">确认修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchForm: {
        date: '',
        state: '',
          channel_id:""
      },
      tableData: [],
      statusOptions: [
        { label: '全部', value: '' },
        { label: '已发放', value: 1 },
        { label: '待发放', value: 0 },
        { label: '不发放', value: 2 }
      ],
      currentPage: 1,
      pageSize: 15,
      total: 0,
      // 新增的数据
      amountDialogVisible: false,
      confirmDialogVisible: false,
      editForm: {
        userId: '',
        username: '',
        originalAmount: 0,
        newAmount: 0,
        rowIndex: -1
      },
        qudaoList:[],
        isEditing: {}
    }
  },
  created() {
    this.getTableData()
    this.fetchAdminList1()
  },
  methods: {
      exportToExcel() {
          // 从本地存储中获取 userInfo
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          if (!userInfo || !userInfo.token) {
              // 如果 token 不存在，给出提示
              this.$message.error('token 不存在，请重新登录');
              return;
          }
          const token = userInfo.token;
          // 拼接搜索条件参数
          let queryParams = `token=${token}`;
          const {state , search , date} = this.searchForm;
          if (state !== undefined && state !== null && state !== '') {
              queryParams += `&state=${state}`;
          }

          if (search !== undefined && search !== null && search !== '') {
              queryParams += `&search=${search}`;
          }

          if (date !== undefined && date !== null && date !== '') {
              queryParams += `&date=${date}`;
          }
          // 构造完整的 URL
          // const url = `http://localhost:8081/admin/UserWeightDiv/userWeightDivExport?${queryParams}`;
          const url = this.$appConfig.baseUrl + `admin/UserWeightDiv/userWeightDivExport?${queryParams}`;
          // 在新窗口中打开页面
          window.open(url, '_blank');
      },
      getStatusType(status) {
          switch (status) {
              case '0': return 'info';
              case '1': return 'success';
              case '2': return 'warning';
              default: return 'info';
          }
      },

      // 根据状态值获取标签效果
      getStatusEffect(status) {
          return status === '2' ? 'dark' : 'light';
      },

      // 根据状态值获取显示文本
      getStatusText(status) {
          const statusMap = {
              '0': '待发放',
              '1': '已发放',
              '2': '不发放'
          };
          return statusMap[status] || '未知';
      },

      // 调用后端接口更新状态
      changeLevel(id, status) {
          this.$http.post('/admin/UserWeightDiv/setUserWeightDivState', {id:id,state:status}).then(result => {
              if(result.code === 200){

                  this.getTableData()
              }
          });
          // 这里调用你的 changeLevel 方法
     },
      fetchAdminList1() {
          const params = {
              type: 3,
              page: this.currentPage,
              limit: this.pageSize
          };
          this.$http.get('/admin/single/lists', {params}).then(result => {
              console.log(result)
              const newArr = []
              if(result.code === 200){
                  result.data.data.forEach(item=>{
                      newArr.push({name:item.name,id:item.id})
                  })
                  console.log(newArr)
                  this.qudaoList = newArr
              }
          });
      },
    getTableData(params = {}) {
        const defaultParams = {
            page: this.currentPage,
            ...params
        };
        this.$message.info({
            message: '正在加载数据...',
            duration: 0,
            showClose: true,
            iconClass: 'el-icon-loading'
        });
        this.$http.get('/admin/UserWeightDiv/lists',{params: defaultParams}).then(result => {
            if (result.code === 200) {
                this.tableData = result.data.data;
                this.total = result.data.total || this.tableData.length;
            } else {
                this.$message.error(result.msg);
            }
        }).catch(error => {
            console.error('获取列表失败:', error);
            this.$message.error('获取数据失败，请重试');
        }).finally(() => {
            this.$message.closeAll();
        });
    },
    toggleStatus(row) {
      row.status = row.status ? 0 : 1
    },
    handleSearch() {
        this.searchParams = {
            ...this.searchForm,
        };
        this.currentPage = 1;
      this.getTableData(this.searchParams)
    },
    handleReset() {
      this.searchForm = {
        date: '',
        state: '',
          channel_id:""
      }
      this.getTableData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData()
    },
    // 点击金额处理
    handleAmountClick(row) {
      this.editForm = {
        userId: row.userId,
        username: row.username || '未知用户',
        originalAmount: row.amount.toFixed(2),
        newAmount: row.amount.toFixed(2),
        rowIndex: this.tableData.indexOf(row)
      }
      this.amountDialogVisible = true
    },
    // 确认修改处理
    handleConfirmEdit() {
      if (!this.editForm.newAmount) {
        this.$message.error('请输入新金额')
        return
      }
      this.confirmDialogVisible = true
    },
    // 处理对话框关闭
    handleDialogClose() {
      this.amountDialogVisible = false
    },
    // 提交金额修改
    submitAmountChange() {
      const index = this.editForm.rowIndex
      if (index > -1 && index < this.tableData.length) {
        this.tableData[index].amount = parseFloat(this.editForm.newAmount)
        this.$message.success('金额修改成功')
      } else {
        this.$message.error('修改失败，找不到对应记录')
      }
      this.confirmDialogVisible = false
      this.amountDialogVisible = false
    }
  }
}
</script>

<style scoped lang="less">
.admin-page {
  padding: 20px;

  .search-label {
    margin-right: 10px;
    color: #606266;
  }

  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }

  .clickable-amount {
    color: #409EFF;
    cursor: pointer;
    font-weight: bold;

    &:hover {
      text-decoration: underline;
    }
  }
}

.amount-edit-dialog {
  border-radius: 8px;
  overflow: hidden;

  /deep/ .el-dialog__header {
    background-color: #f5f7fa;
    padding: 15px 20px;

    .el-dialog__title {
      font-weight: bold;
      color: #303133;
    }
  }

  /deep/ .el-dialog__body {
    padding: 25px 20px 10px;
  }

  .edit-form {
    margin-top: 10px;

    /deep/ .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }

    .info-item {
      /deep/ .el-input__inner {
        background-color: #f5f7fa;
        color: #606266;
      }
    }
  }

  /deep/ .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
  }

  .dialog-footer {
    text-align: right;
  }
}

.confirm-dialog {
  border-radius: 8px;

  /deep/ .el-dialog__header {
    padding: 15px 20px;
  }

  /deep/ .el-dialog__body {
    padding: 10px 40px;
  }

  .confirm-content {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    .warning-icon {
      font-size: 24px;
      color: #E6A23C;
      margin-right: 15px;
      margin-top: 3px;
    }

    .confirm-text {
      flex: 1;

      .confirm-title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 5px;
      }

      .confirm-desc {
        color: #606266;
        line-height: 1.5;
      }
    }
  }

  .confirm-details {
    background-color: #f8f8f8;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 10px;

    .detail-item {
      display: flex;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .detail-label {
        width: 70px;
        color: #909399;
      }

      .detail-value {
        flex: 1;
        color: #303133;
        font-weight: 500;
      }
    }
  }
}

/deep/ .el-dialog__header{
    padding: 10px !important;
}
</style>
